package capstone.android.application.nalg.activity;

import java.util.ArrayList;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import capstone.android.application.nalg.R;
import capstone.android.application.nalg.data.GsonHandler;
import capstone.android.application.nalg.helpers.ConnectionManager;
import capstone.android.application.nalg.model.Event;
import capstone.android.application.nalg.model.Profile;

import com.google.gson.Gson;

public class ProfileManagerActivity extends Activity {

	private String androidId = null;
	private GsonHandler gson = null;
	private Gson jsonFactory = null;
	private Profile curProfile = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_profile_manager);
		setRequestedOrientation(1);
		
		jsonFactory = new Gson();
		gson = new GsonHandler(getApplicationContext());
		androidId = getIntent().getExtras().getString("CURRENT_USER_ID");
		try {
			curProfile = gson.loadProfile();
//			Toast.makeText(this, "ID: " + curProfile.getId(), Toast.LENGTH_LONG).show();
		} catch (Exception ex) {
			curProfile = new Profile(androidId);
		}
		
		populateFields();
	}

	private void populateFields(){
		try{
		((TextView) findViewById(R.id.profileNameField)).setText(curProfile.getName());
		((TextView) findViewById(R.id.profileBiographyField)).setText(curProfile.getBio());
		((TextView) findViewById(R.id.profileCorporationField)).setText(curProfile.getCorporation());
		((TextView) findViewById(R.id.profilePhoneField)).setText(String.valueOf(curProfile.getPhoneNumber()));
		((TextView) findViewById(R.id.profileZipField)).setText(String.valueOf(curProfile.getZipcode()));
		} catch (Exception ex){
//			Log.e("ProfileManager", ex.getMessage());
		}
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.profile_manager, menu);
		return true;
	}
	public void saveProfile(View view){
//		Intent intent = new Intent(this, DashboardActivity.class);
//		intent.putExtra("CURRENT_USER_ID", androidId);
//		Profile curUser = buildCurrentUser(androidId);
//		gson.updateLocalUserProfile(curUser);
//		startActivity(intent);
		new LongOperation().execute("postProfile");
	}
	private Profile buildCurrentUser(String userId){
		Profile p = new Profile(userId);
		
		p.setName(((TextView) findViewById(R.id.profileNameField)).getText().toString());
		p.setBio(((TextView) findViewById(R.id.profileBiographyField)).getText().toString());
		p.setCorporation(((TextView) findViewById(R.id.profileCorporationField)).getText().toString());
		p.setPhoneNumber(Long.parseLong(((TextView) findViewById(R.id.profilePhoneField)).getText().toString()));
		p.setZipcode(Integer.parseInt(((TextView) findViewById(R.id.profileZipField)).getText().toString()));
		
		Profile curProf = gson.loadProfile();
		if (curProf != null)
			p.setEvents(curProf.getEvents());
		else
			p.setEvents(new ArrayList<Event>());
		
		return p;		
	}
	
	public void goHome(View view)
	{
//		curProfile = new Profile(androidId);
//		curProfile.setName("Daniel");
//		sendJson("http://208.186.227.99:3000/profile/", jsonFactory.toJson(curProfile, Profile.class), getApplicationContext());
		
		new LongOperation().execute("sendToDb");
	}
	

	
	private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
        	String json = "";
//    		curProfile = new Profile(androidId);
//    		curProfile.setName("Daniel");
        	for (String s : params)
        	{
        		if (s.equals("postProfile"))
        		{
		        	curProfile = buildCurrentUser(androidId);
		        	json = ConnectionManager.sendJson("http://208.186.227.99:3000/profile/", jsonFactory.toJson(curProfile, Profile.class), getApplicationContext());
        		}
        		if (s.equals("sendToDb"))
        		{
        			json = ConnectionManager.sendToDb("http://208.186.227.99:3000", androidId, getApplicationContext());
        		}
        	}
        	if(json == ""){
        		json = jsonFactory.toJson(buildCurrentUser(androidId), Profile.class);
        	}
            return json.toString();
        }

        @Override
        protected void onPostExecute(String result) {
        	Profile p = null;
        	if (result != ""){
        		p = jsonFactory.fromJson(result, Profile.class);
        	}
        	else
        		p = gson.loadProfile();
        	gson.saveProfile(p);

        	TextView name = (TextView) findViewById(R.id.profileNameField);
        	TextView bio = (TextView) findViewById(R.id.profileBiographyField);
        	TextView phone = (TextView) findViewById(R.id.profilePhoneField);
        	TextView zipcode = (TextView) findViewById(R.id.profileZipField);
        	TextView corporation = (TextView) findViewById(R.id.profileCorporationField);
            
        	name.setText(p.getName()); 
            bio.setText(p.getBio());
            phone.setText(String.valueOf(p.getPhoneNumber()));
            zipcode.setText(String.valueOf(p.getZipcode()));
            corporation.setText(p.getCorporation());
            
            
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }
}
